home *** CD-ROM | disk | FTP | other *** search
/ PC World Komputer 2010 April / PCWorld0410.iso / hity wydania / Ubuntu 9.10 PL / karmelkowy-koliberek-9.10-netbook-remix-PL.iso / casper / filesystem.squashfs / usr / share / pyshared / nevow / context.py < prev    next >
Text File  |  2009-03-23  |  12KB  |  339 lines

  1. # -*- test-case-name: nevow.test.test_context -*-
  2. # Copyright (c) 2004 Divmod.
  3. # See LICENSE for details.
  4.  
  5. from __future__ import generators
  6.  
  7. import warnings
  8.  
  9. from nevow import stan
  10. from nevow.inevow import IData, IRequest
  11. from nevow.stan import Unset
  12. from nevow.util import qual
  13.  
  14. from zope.interface import providedBy
  15. # TTT: Move to web2.context
  16.  
  17. def megaGetInterfaces(adapter):
  18.     return [qual(x) for x in providedBy(adapter)]
  19.  
  20. dataqual = qual(IData)
  21.  
  22. class WebContext(object):
  23.     _remembrances = None
  24.     tag = None
  25.     _slotData = None
  26.     parent = None
  27.     locateHook = None
  28.  
  29.     # XXX: can we get rid of these somehow?
  30.     isAttrib = property(lambda self: False)
  31.     inURL = property(lambda self: False)
  32.     inJS = property(lambda self: False)
  33.     inJSSingleQuoteString = property(lambda self: False)
  34.  
  35.     precompile = property(lambda self: False)
  36.  
  37.     def arg(self, get, default=None):
  38.         """Placeholder until I can find Jerub's implementation of this
  39.  
  40.         Return a single named argument from the request arguments
  41.         """
  42.         req = self.locate(IRequest)
  43.         return req.args.get(get, [default])[0]
  44.  
  45.     def __init__(self, parent=None, tag=None, remembrances=None):
  46.         self.tag = tag
  47.         sd = getattr(tag, 'slotData', None)
  48.         if sd is not None:
  49.             self._slotData = sd
  50.         self.parent = parent
  51.         self._remembrances = remembrances
  52.  
  53.     def remember(self, adapter, interface=None):
  54.         """Remember an object that implements some interfaces.
  55.         Later, calls to .locate which are passed an interface implemented
  56.         by this object will return this object.
  57.  
  58.         If the 'interface' argument is supplied, this object will only
  59.         be remembered for this interface, and not any of
  60.         the other interfaces it implements.
  61.         """
  62.         if interface is None:
  63.             interfaceList = megaGetInterfaces(adapter)
  64.             if not interfaceList:
  65.                 interfaceList = [dataqual]
  66.         else:
  67.             interfaceList = [qual(interface)]
  68.         if self._remembrances is None:
  69.             self._remembrances = {}
  70.         for interface in interfaceList:
  71.             self._remembrances[interface] = adapter
  72.         return self
  73.  
  74.     def locate(self, interface, depth=1, _default=object()):
  75.         """Locate an object which implements a given interface.
  76.         Objects will be searched through the context stack top
  77.         down.
  78.         """
  79.         key = qual(interface)
  80.         currentContext = self
  81.         while True:
  82.             if depth < 0:
  83.                 full = []
  84.                 while True:
  85.                     try:
  86.                         full.append(self.locate(interface, len(full)+1))
  87.                     except KeyError:
  88.                         break
  89.                 #print "full", full, depth
  90.                 if full:
  91.                     return full[depth]
  92.                 return None
  93.  
  94.             _remembrances = currentContext._remembrances
  95.             if _remembrances is not None:
  96.                 rememberedValue = _remembrances.get(key, _default)
  97.                 if rememberedValue is not _default:
  98.                     depth -= 1
  99.                     if not depth:
  100.                         return rememberedValue
  101.  
  102.             # Hook for FactoryContext and other implementations of complex locating
  103.             locateHook = currentContext.locateHook
  104.             if locateHook is not None:
  105.                 result = locateHook(interface)
  106.                 if result is not None:
  107.                     currentContext.remember(result, interface)
  108.                     return result
  109.  
  110.             contextParent = currentContext.parent
  111.             if contextParent is None:
  112.                 raise KeyError, "Interface %s was not remembered." % key
  113.  
  114.             currentContext = contextParent
  115.  
  116.     def chain(self, context):
  117.         """For nevow machinery use only.
  118.  
  119.         Go to the top of this context's context chain, and make
  120.         the given context the parent, thus continuing the chain
  121.         into the given context's chain.
  122.         """
  123.         top = self
  124.         while top.parent is not None:
  125.             if top.parent.tag is None:
  126.                 ## If top.parent.tag is None, that means this context (top)
  127.                 ## is just a marker. We want to insert the current context
  128.                 ## (context) as the parent of this context (top) to chain properly.
  129.                 break
  130.             top = top.parent
  131.             if top is context: # this context is already in the chain; don't create a cycle
  132.                 return
  133.         top.parent = context
  134.  
  135.     def fillSlots(self, name, stan):
  136.         """Set 'stan' as the stan tree to replace all slots with name 'name'.
  137.         """
  138.         if self._slotData is None:
  139.             self._slotData = {}
  140.         self._slotData[name] = stan
  141.  
  142.     def locateSlotData(self, name):
  143.         """For use by nevow machinery only, or for some fancy cases.
  144.  
  145.         Find previously remembered slot filler data.
  146.         For use by flatstan.SlotRenderer"""
  147.         currentContext = self
  148.         while True:
  149.             if currentContext._slotData:
  150.                 data = currentContext._slotData.get(name, Unset)
  151.                 if data is not Unset:
  152.                     return data
  153.             if currentContext.parent is None:
  154.                 raise KeyError, "Slot named '%s' was not filled." % name
  155.             currentContext = currentContext.parent
  156.  
  157.     def clone(self, deep=True, cloneTags=True):
  158.         ## don't clone the tags of parent contexts. I *hope* code won't be
  159.         ## trying to modify parent tags so this should not be necessary.  We
  160.         ## used to also clone parent contexts, but that is insanely expensive.
  161.         ## The only code that actually required that behavior is
  162.         ## ContextSerializer, which is the only caller of context.chain.  So
  163.         ## instead of doing the clone here, now we do it there.
  164.  
  165.         if self.parent is not None:
  166.             if deep:
  167.                 parent = self.parent.clone(cloneTags=False)
  168.             else:
  169.                 parent = self.parent
  170.         else:
  171.             parent = None
  172.  
  173.         if cloneTags:
  174.             tag = self.tag.clone(deep=deep)
  175.         else:
  176.             tag = self.tag
  177.  
  178.         if self._remembrances is not None:
  179.             remembrances = self._remembrances.copy()
  180.         else:
  181.             remembrances = None
  182.  
  183.         return type(self)(
  184.             parent=parent,
  185.             tag=tag,
  186.             remembrances=remembrances,
  187.         )
  188.  
  189.     def __conform__(self, interface):
  190.         """Support IFoo(ctx) syntax.
  191.         """
  192.         try:
  193.             return self.locate(interface)
  194.         except KeyError:
  195.             return None
  196.  
  197.     def __repr__(self):
  198.         rstr = ''
  199.         if self._remembrances:
  200.             rstr = ', remembrances=%r' % self._remembrances
  201.         return "%s(tag=%r%s)" % (self.__class__.__name__, self.tag, rstr)
  202.  
  203.  
  204. class FactoryContext(WebContext):
  205.     """A context which allows adapters to be registered against it so that an object
  206.     can be lazily created and returned at render time. When ctx.locate is called
  207.     with an interface for which an adapter is registered, that adapter will be used
  208.     and the result returned.
  209.     """
  210.     inLocate = 0
  211.     
  212.     def locateHook(self, interface):
  213.  
  214.         ## Prevent infinite recursion from interface(self) calling self.getComponent calling self.locate
  215.         self.inLocate += 1
  216.         adapter = interface(self, None)
  217.         self.inLocate -= 1
  218.         
  219.         return adapter
  220.  
  221.     def __conform__(self, interface):
  222.         if self.inLocate:
  223.             return None
  224.         return WebContext.__conform__(self, interface)
  225.  
  226. class SiteContext(FactoryContext):
  227.     """A SiteContext is created and installed on a NevowSite upon initialization.
  228.     It will always be used as the root context, and can be used as a place to remember
  229.     things sitewide.
  230.     """
  231.     pass
  232.  
  233.  
  234. class RequestContext(FactoryContext):
  235.     """A RequestContext has adapters for the following interfaces:
  236.  
  237.     ISession
  238.     IFormDefaults
  239.     IFormErrors
  240.     IHand
  241.     IStatusMessage
  242.     """
  243.     pass
  244.  
  245. def getRequestContext(self):
  246.     top = self.parent
  247.     while not isinstance(top, RequestContext):
  248.         top = top.parent
  249.     return top
  250.  
  251. class PageContext(FactoryContext):
  252.     """A PageContext has adapters for the following interfaces:
  253.  
  254.     IRenderer
  255.     IRendererFactory
  256.     IData
  257.     """
  258.  
  259.     def __init__(self, *args, **kw):
  260.         FactoryContext.__init__(self, *args, **kw)
  261.         if self.tag is not None and hasattr(self.tag, 'toremember'):
  262.             for i in self.tag.toremember:
  263.                 self.remember(*i)
  264.  
  265. # TTT: To stay here.
  266. NodeNotFound = stan.NodeNotFound # XXX: DeprecationWarning?
  267. TooManyNodes = stan.TooManyNodes # XXX: DeprecationWarning?
  268.  
  269. class WovenContext(WebContext):
  270.     key = None
  271.     isAttrib = False
  272.     inURL = False
  273.     precompile = False
  274.     inJS = False
  275.     inJSSingleQuoteString = False
  276.  
  277.     def __init__(self, parent=None, tag=None, precompile=None, remembrances=None, key=None, isAttrib=None, inURL=None, inJS=None, inJSSingleQuoteString=None):
  278.         WebContext.__init__(self, parent, tag, remembrances)
  279.         if self.parent:
  280.             self.precompile = parent.precompile
  281.             self.isAttrib = parent.isAttrib
  282.             self.inURL = parent.inURL
  283.             self.inJS = parent.inJS
  284.             self.inJSSingleQuoteString = parent.inJSSingleQuoteString
  285.  
  286.         if self.tag is not None:
  287.             if self.tag.remember is not Unset:
  288.                 self.remember(tag.remember)
  289.             if key is None:
  290.                 key = self.tag.key
  291.  
  292.         if key is not None and key is not Unset:
  293.             if self.parent is not None and getattr(self.parent, 'key', None):
  294.                 self.key = '.'.join((self.parent.key, key))
  295.             else:
  296.                 self.key = key
  297.             #print "KEY", `self.key`
  298.         else:
  299.             ## Bubble the value down to the bottom so it's always immediately accessible
  300.             if self.parent is not None:
  301.                 self.key = getattr(self.parent, 'key', '')
  302.  
  303.         if precompile is not None: self.precompile = precompile
  304.         if isAttrib is not None: self.isAttrib = isAttrib
  305.         if inURL is not None: self.inURL = inURL
  306.         if inJS is not None: self.inJS = inJS
  307.         if inJSSingleQuoteString is not None: self.inJSSingleQuoteString = inJSSingleQuoteString
  308.  
  309.     def __repr__(self):
  310.         rstr = ''
  311.         if self._remembrances:
  312.             rstr = ', remembrances=%r' % self._remembrances
  313.         attribstr=''
  314.         if self.isAttrib:
  315.             attribstr=", isAttrib=True"
  316.         urlStr = ''
  317.         if self.inURL:
  318.             urlStr = ', inURL=True'
  319.         return "%s(tag=%r%s%s%s)" % (self.__class__.__name__, self.tag, rstr,attribstr,urlStr)
  320.  
  321.     def patternGenerator(self, pattern, default=None):
  322.         warnings.warn("use Tag.patternGenerator instead", DeprecationWarning, stacklevel=2)
  323.         return self.tag.patternGenerator(pattern, default)
  324.  
  325.     def allPatterns(self, pattern):
  326.         warnings.warn("use Tag.allPatterns instead", DeprecationWarning, stacklevel=2)
  327.         return self.tag.allPatterns(pattern)
  328.  
  329.     def onePattern(self, pattern):
  330.         warnings.warn("use Tag.onePattern instead", DeprecationWarning, stacklevel=2)
  331.         return self.tag.onePattern(pattern)
  332.  
  333.     def clone(self, deep=True, cloneTags=True):
  334.         cloned = WebContext.clone(self, deep, cloneTags)
  335.         cloned.isAttrib = self.isAttrib
  336.         cloned.inURL = self.inURL
  337.         return cloned
  338.         
  339.